import { useNavigate, useParams, Outlet } from 'react-router-dom';
import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import UserABI from './contract/ABIs/User.json'; // 用户合约 ABI
import MarketplaceABI from './contract/ABIs/Marketplace.json'; // 用户列表合约 ABI
import MaterialListAddr from './contract/ADDRESSes/MaterialListAddr';

import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
} from '@ant-design/icons';
import { Breadcrumb, Layout, Menu, Button } from 'antd';
import './index1.css'; // 确保在此文件中包含了必要的样式
import axios from 'axios';

const { Header, Content, Footer, Sider } = Layout;

function getItem(label, key, icon, children) {
  return {
    key,
    icon,
    children,
    label,
  };
}

const items = [
  getItem('首页商品展示', '1', <DesktopOutlined />),
  getItem('添加商品', '2', <FileOutlined />),
  getItem('交易记录', '3', <PieChartOutlined />),
  getItem('商家商品管理', '4', <PieChartOutlined />),
  getItem('我的收藏', '5', <MenuUnfoldOutlined />),
  getItem('商品评价', '6', <MenuFoldOutlined />),
];

const Index1 = () => {
  const { userAddr } = useParams();
  const [balance, setBalance] = useState(0);
  const [Username, setUsername] = useState(0);
  const [collapsed, setCollapsed] = useState(false);
  const [xinyong, setxinyong] = useState(0);//信用评分
  const [bian, setbian] = useState(1);//首页进入商品列表
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(true);
  const web3 = new Web3(window.ethereum);
  const userContract = new web3.eth.Contract(UserABI, userAddr);
  const marketplaceContract = new web3.eth.Contract(MarketplaceABI, MaterialListAddr);
  const handleLogout = () => {
    navigate(`/login`);
  };


  useEffect(() => {
    const fetchBalance = async () => {
      const SellerProductListS = [];
      let xinxyong = 0;

      // 监听合约事件
      marketplaceContract.events.ProductPurchased()
        .on('data', (event) => {
          console.log('收到事件：', event.returnValues);
          // 在这里编写处理事件的逻辑，比如将事件信息发送给外部应用程序
        })
      const balance = await userContract.methods.viewBalance().call();
      setBalance(Number(balance));
      console.log("balance", balance)
      const username = await userContract.methods.username().call();
      setUsername(username);
      // 计算商家信用评分
      const accounts = await web3.eth.requestAccounts();
      // 获取所有商品id
      const SellerProductIds = await marketplaceContract.methods.getSellerProductIds().call({ from: accounts[0] });
      for (const key of SellerProductIds) {
        // console.log("key", key)
        const SellerProductList = await marketplaceContract.methods.getSellerReviews(key).call({ from: accounts[0] });
        // 获取已购买的商品id
        const TransactionHistoryList = await marketplaceContract.methods.viewTransactionHistory().call({ from: accounts[0] });
        console.log("TransactionHistoryList", SellerProductList)
        for (const SellerProduct of SellerProductList) {
          if (SellerProduct.reviewer != accounts[0]) {
            SellerProductListS.push(SellerProduct)
            xinxyong += Number(SellerProduct.rating)
          }
        }
        for (const key of TransactionHistoryList) {
          const BuyerReviews = await marketplaceContract.methods.getBuyerReviews(key.productId).call({ from: accounts[0] });
          for (const BuyerReview of BuyerReviews) {
            if (BuyerReview.reviewer != accounts[0]) {
              SellerProductListS.push(BuyerReview)
              xinxyong += Number(BuyerReview.rating)
            }
          }
        }
      }
      setxinyong(xinxyong)

    };
    fetchBalance();
    setIsLoading(false);
  }, [userAddr]);

  useEffect(() => {
    if (bian == 1) {
      navigate('ProductList');
    }
    setbian(bian + 1);
  }, [navigate]);

  const handleMenuClick = (key) => {
    if (key === "1") {
      navigate('ProductList');
    } else if (key === "2") {
      navigate('AddProduct');
    } else if (key === '3') {
      navigate('TransactionHistory');
    } else if (key === '4') {
      // 路径
      navigate('SellerProducts');
    } else if (key === '5') {
      // 路径
      navigate('CollectProductList');
    } else if (key === '6') {
      // 路径
      navigate('BuyerReview');
    }
  }

  return (
    <Layout
      style={{
        minHeight: '100vh',
      }}
    >
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        style={{ backgroundColor: '#6a0dad' }}
      >

        <Menu
          theme="dark"
          defaultSelectedKeys={['1']}
          mode="inline"
          items={items}
          onClick={(e) => handleMenuClick(e.key)}
          style={{ backgroundColor: '#6a0dad', color: '#fff' }}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: 0,
            background: '#6a0dad',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '0 20px',
          }}
        >
          <div className="logo" style={{
            height: '60px',
            width: '60px',
            borderRadius: '50%',
            background: '#fff',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            marginRight: '20px',
          }}>
            <img src="https://img.zcool.cn/community/01ecdf59e70865a801202b0c236fcb.jpg@2o.jpg" alt="Logo" />
          </div>
          <h1 className="header-title" style={{ color: '#fff' }}>先锋二手商城</h1>
          <div className="user-info" style={{ color: '#fff' }}>
            {isLoading ? (
              <div>Loading...</div>
            ) : Username || balance || xinyong ? (
              <div>
                <p>用户名: {Username} 余额：{balance}商家信用评分：{xinyong}   </p>
              </div>
            ) : (
              <div>User not found.</div>
            )}
            <Button type="primary" onClick={handleLogout} style={{ backgroundColor: '#fff', color: '#6a0dad' }}>
              退出
            </Button>
          </div>
        </Header>
        <Content
          style={{
            margin: '0 16px',
          }}
        >
          <Breadcrumb
            style={{
              margin: '16px 0',
              color: '#fff'
            }}
          >
            <Breadcrumb.Item style={{ color: '#fff' }}>用户</Breadcrumb.Item>
          </Breadcrumb>
          <div
            style={{
              padding: 24,
              minHeight: 360,
              background: '#fff',
              borderRadius: '10px',
            }}
          >
            <Outlet />
          </div>
        </Content>
        <Footer
          style={{
            textAlign: 'center',
            backgroundColor: '#6a0dad',
            color: '#fff',
          }}
        >
          Ant Design ©{new Date().getFullYear()} Created by Ant UED
        </Footer>
      </Layout>
    </Layout>
  );
};

export default Index1;
